﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;

namespace Portal.CMS
{
    public class UpdateRelationNews : WebPart
    {
        public override string WebPartId
        {
            get
            {
                return "UpdateRelationNews";
            }
        }

        public override string Title
        {
            get
            {
                return ResourceBLL.GetText(WebPartId,"Title","Cập nhật tin tức liên quan");
            }
        }

        public override string Description
        {
            get
            {
                return ResourceBLL.GetText(WebPartId,"Description","");
            }
        }

       
        public override void LoadSubControls(System.Web.UI.WebControls.PlaceHolder pl, System.Web.UI.Page Page, LoadParamCls LoadParamCls)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(UpdateRelationNews));
            string GroupNewsId = (string)System.Web.HttpContext.Current.Request["GroupNewsId"];
            string NewsId = (string)System.Web.HttpContext.Current.Request["NewsId"];
            NewsCls NewsCls = new NewsBLL().CreateModel(Environment.Environments.ActiveLanguage, NewsId);

            string RetHtml=
                Environments.GetFormDialog(
                    "<div class=cssHeading>"+NewsCls.Subject+"</div>\r\n"+
                    "<div id=\"divNewsRelations\">" + GetNewsRelationForm(NewsCls.belongSite, NewsCls) + "</div><div id=divAlreadyNewsRelation>"+GetAlreadyNewsRelation(NewsId)+"</div>",Title);
            pl.Controls.Add(new System.Web.UI.LiteralControl(RetHtml));
        }

        [AjaxPro.AjaxMethod]
        public string GetAlreadyNewsRelation(string NewsId)
        {
            DataTable dtNewsRelation = new NewsBLL().ReadingNewsRelation(NewsId);

            string RetHtml = "<div class=cssHeading>" + GetText("NewsRelationListHeading", "Danh sách tin liên quan") + " (" + dtNewsRelation.Rows.Count.ToString("#,##0") + ")</div>";
            
            if (dtNewsRelation.Rows.Count == 0)
            {
                RetHtml += "<div class=\"cssNoDataRelation\">" + ResourceBLL.GetText(WebPartId, "cssNoDataRelation", "Chưa có tin nào liên quan!") + "</div>";
            }
            else
            {
                   RetHtml+=
                           "<div><input type=\"hidden\" id=\"txtMaxRelationNews\" value=\""+dtNewsRelation.Rows.Count+"\"><input type=\"button\" onclick=\"javascript:ClientSaveIndexRelationNews('"+NewsId+"');\" value=\""+GetText("saveIndexRelationNews","Cập nhật thứ tự hiện thị")+"\"></div>\r\n"+
                           "<table class=cssNewsContent>" +
                           "  <tr>" +
                           "      <th class=cssCol0>#</th>" +
                           "      <th class=cssCol1>" + ResourceBLL.GetText(WebPartId, "SubjectText", "Tiêu đề") + "</th>" +
                           "      <th class=cssCol2>"+ ResourceBLL.GetText(WebPartId, "EntryDate", "Ngày tạo") + "</th>" +
                           "      <th class=cssCol3></th>" +
                           " </tr>";
                for (int iIndex = 0; iIndex < dtNewsRelation.Rows.Count; iIndex++)
                {
                    string NewsRelationId = (string)dtNewsRelation.Rows[iIndex]["NewsRelationId"];
                    string SubjectText = "";
                    try
                    {
                        SubjectText = (string)dtNewsRelation.Rows[iIndex]["Subject"];
                    }
                    catch { }

                    DateTime EntryDate = (DateTime)dtNewsRelation.Rows[iIndex]["EntryDate"];
                    
                    RetHtml +=
                           "  <tr onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal'\">" +
                           "      <td valign=top><input type=hidden id=\"txtRelationNewsId" + iIndex + "\" value=\"" + NewsRelationId + "\"> <input class=\"cssIndexRelationNews\" id=\"txtIndex" + iIndex + "\" value=\"" + (iIndex + 1) + "\"></td>" +
                           "      <td valign=top>" + SubjectText + "</td>" +
                           "      <td valign=top>"+EntryDate.ToString("dd/MM/yyyy HH:mm")+"</td>" +
                           "      <td valign=top><a href=\"javascript:ClientRemoveNewsRelation('" + NewsRelationId + "');\">" + ResourceBLL.GetText(WebPartId, "RemoveText", "Loại bỏ") + "</a></td>" +
                           " </tr>";
                }
                RetHtml += "</table>";
            }
            return RetHtml;
        }

        string GetNewsRelationForm(string ActiveSite,NewsCls NewsCls)
        {
            //doan nay lam qua form search giong ben news...

            string SelectSite =
                 "<select id=drpSelectSiteForSearchNews onchange=javascript:ClientSearchNewsRelation();>";
            string[] Sites = Environments.GetSites();
            for (int iIndex = 0; iIndex < Sites.Length; iIndex++)
            {
                if (Sites[iIndex].ToLower().Equals(ActiveSite))
                {
                    SelectSite += "<option selected value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
                }
                else
                {
                    SelectSite += "<option value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
                }
            }
            SelectSite += "</select>";


            string SelectWorkFlowStatusText =
                "<select id=drpSelectWorkflowStatus>" +
                "   <option value=\"0\">" + ResourceBLL.GetText(WebPartId, "NotPublishingComboxItem", "Chưa phát hành") + "</option>" +
                "   <option value=\"1\">" + ResourceBLL.GetText(WebPartId, "PublishingComboxItem", "Đã phát hành") + "</option>" +
                "</select>";

            string RetHtml =
                WebPartUtilities.AttachJavascript("Portal.CMS", "News.js") +
                    "<div class=cssHeading>"+GetText("SearchNewsTitle","Tìm kiếm tin")+"</div>\r\n"+
                    "<input id=\"txtSrcNewsId\" type=hidden value=\"" + NewsCls.NewsId + "\">\r\n" +
                    "<table>" +
                    "   <tr>" +
                    "       <td>" + ResourceBLL.GetText(WebPartId, "Site", "Site") + "</td>" +
                    "       <td>" + SelectSite + "</td>" +
                    "   </tr>" +
                    "   <tr>" +
                    "       <td>" + ResourceBLL.GetText(WebPartId, "Keyword", "Từ khóa") + "</td>" +
                    "       <td><input class=cssSearchNewsKeyword id=txtSearchKeyword value=\"\"></td>" +
                    "   </tr>" +
                    "   <tr>" +
                    "       <td>" + ResourceBLL.GetText(WebPartId, "Time", "Thời gian") + "</td>" +
                    "       <td>" + Environment.LookUpUtilities.GenerateLookUpDate("txtFromDate", "") + " ~ " + Environment.LookUpUtilities.GenerateLookUpDate("txtToDate", "") + "</td>" +
                    "   </tr>" +
                    "   <tr>" +
                    "       <td>" + ResourceBLL.GetText(WebPartId, "Source", "Nguồn") + "</td>" +
                    "       <td><input id=txtSource value=\"\"></td>" +
                    "   </tr>" +
                    "   <tr>" +
                    "       <td>" + ResourceBLL.GetText(WebPartId, "GroupNewsItem", "Nhóm") + "</td>" +
                    "       <td><div id=divSelectGroupNewsItem>" + ServerSideGetGroupNewsItem(ActiveSite, "") + "</div></td>" +
                    "   </tr>" +
                    "   <tr>" +
                    "       <td>" + ResourceBLL.GetText(WebPartId, "Status", "Trạng thái") + "</td>" +
                    "       <td>" + SelectWorkFlowStatusText + "</td>" +
                    "   </tr>" +
                      "   <tr>" +
                    "       <td></td>" +
                    "       <td><input type=button onclick=javascript:ClientSearchNewsRelation(); value=\"" + ResourceBLL.GetText(WebPartId, "Search", "Tìm kiếm") + "\"></td>" +
                    "   </tr>" +
                    "</table>" +
                    "<div id=\"divProcessing\"></div>" +
                    "<div id=divSearchNewsContent></div>";

            return RetHtml;
        }



        [AjaxPro.AjaxMethod]
        public string SearchRelationNews(
            string SrcNewsId,
            string belongSite,
            string Keyword,
            string fromDate,
            string toDate,
            int WorkflowStatusIndex,
            string SGroupNewsItemId,
            string Source,
            int PageIndex)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                //if(Keyword.Trim().Length==0 && Source.Trim().Length==0)throw new Exception(ResourceBLL.GetText(WebPartId,"KeywordIsMissing","Chưa nhập từ khóa tìm kiếm..."));
                string RetHtml = "";
                Keyword = Environment.WebPartUtilities.CorrectForSearch(Keyword);
                Source = Environment.WebPartUtilities.CorrectForSearch(Source);
                fromDate = Environment.WebPartUtilities.CorrectForSearch(fromDate);
                toDate = Environment.WebPartUtilities.CorrectForSearch(toDate);

                DataTable dtNews = new NewsBLL().SearchingForRelation(SrcNewsId, belongSite, Keyword, fromDate, toDate, WorkflowStatusIndex, Source, SGroupNewsItemId);
                int ItemPerPage = 20;
                int MaxPage = dtNews.Rows.Count / ItemPerPage;
                if (dtNews.Rows.Count % ItemPerPage != 0) MaxPage++;
                int StartIndex = PageIndex * ItemPerPage;
                int EndIndex = StartIndex + ItemPerPage;
                if (EndIndex > dtNews.Rows.Count) EndIndex = dtNews.Rows.Count;
                string SelectPageText =
                   ResourceBLL.GetText(WebPartId, "PageText", "Trang") + ": <select id=divSelectSearchNewsPage>";
                for (int iIndex = 0; iIndex < MaxPage; iIndex++)
                {
                    if (PageIndex == iIndex)
                    {
                        SelectPageText += "<option selected>" + (iIndex + 1) + "</option>";
                    }
                    else
                    {
                        SelectPageText += "<option>" + (iIndex + 1) + "</option>";
                    }
                }
                SelectPageText += "</select><input type=button value=\"Go\" onclick=javascript:ClientSearchNewsRelation();>";
                if (MaxPage <= 1) SelectPageText = "";


                if (dtNews.Rows.Count == 0)
                {
                    RetHtml += "<div class=\"cssNoDataSearchNews\">" + ResourceBLL.GetText(WebPartId, "cssNoDataSearchNews", "Không có tin tức nào thỏa mãn điều kiện tìm kiếm!") + "</div>";
                }
                else
                {
                    RetHtml += SelectPageText+
                    "<table class=cssNewsContent>" +
                           "  <tr>" +
                           "      <th class=cssCol0>#</th>" +
                           "      <th class=cssCol1>" + ResourceBLL.GetText(WebPartId, "SubjectText", "Tiêu đề") + "</th>" +
                           "      <th class=cssCol2></th>" +
                           " </tr>";
                    for (int iIndex = StartIndex; iIndex < EndIndex; iIndex++)
                    {
                        string DestNewsId = (string)dtNews.Rows[iIndex]["NewsId"];
                        string GroupNewsId = (string)dtNews.Rows[iIndex]["GroupNewsId"];
                        string GroupNewsItemId = (string)dtNews.Rows[iIndex]["GroupNewsItemId"];
                        string SubjectText = "";
                        try
                        {
                            SubjectText = (string)dtNews.Rows[iIndex][Environments.ActiveLanguage + "Subject"];
                        }
                        catch { }
                        

                        RetHtml +=
                               "  <tr onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal'\">" +
                               "      <td valign=top>" + (iIndex + 1) + "</td>" +
                               "      <td valign=top class=cssTdSubjectText>" + SubjectText + "</td>" +
                               "      <td valign=top nowrap><div id=\"divAddNewsRelationItem_"+DestNewsId+"\"><a href=\"javascript:ClientAddNewsRelation('"+ DestNewsId + "');\">" + ResourceBLL.GetText(WebPartId, "AddNewsRelation", "Đưa vào") + "</a></div></td>" +
                               " </tr>";
                    }
                    RetHtml += "</table>";
                }
                return RetHtml;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideGetGroupNewsItem(string belongSite, string SGroupNewsItemId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                string SelectGroupNewsText =
                   "<select id=drpSelectGroupNewsItem>";
                DataTable dtGroupNewsItems = new GroupNewsBLL().ReadingGroupNewsItemsForSearch(belongSite);
                for (int iIndex = 0; iIndex < dtGroupNewsItems.Rows.Count; iIndex++)
                {
                    string GroupNewsItemName = (string)dtGroupNewsItems.Rows[iIndex][Environments.ActiveLanguage + "GroupNewsItemName"];
                    string GroupNewsItemId = (string)dtGroupNewsItems.Rows[iIndex]["GroupNewsItemId"];
                    if (GroupNewsItemId.Equals(SGroupNewsItemId))
                    {
                        SelectGroupNewsText += "<option selected value=\"" + GroupNewsItemId + "\">" + GroupNewsItemName + "</option>";
                    }
                    else
                    {
                        SelectGroupNewsText += "<option  value=\"" + GroupNewsItemId + "\">" + GroupNewsItemName + "</option>";
                    }
                }
                SelectGroupNewsText += "</select>";
                if (dtGroupNewsItems.Rows.Count == 0) SelectGroupNewsText = "?";
                return SelectGroupNewsText;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideNews(
            string ActiveLanguage, 
            string NewsId, 
            string Subject, 
            string ImageUrl, 
            string ShortContent, 
            string Body, 
            string SearchKeyword, 
            string Source,
            string sEntryDate,
            bool AttachedDoc,
            bool AttachedImage,
            bool AttachedVideo)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                if (Subject.Trim().Length == 0) throw new Exception(ResourceBLL.GetText(WebPartId,"EnterSubject","Nhập tiêu đề!"));
                if (ShortContent.Trim().Length == 0) throw new Exception(ResourceBLL.GetText(WebPartId,"InputShortContent","Nhập mô tả!"));
                if (Body.Trim().Length == 0) throw new Exception(ResourceBLL.GetText(WebPartId,"InputBody","Nhập nội dung!"));

                ShortContent = System.Web.HttpUtility.HtmlDecode(ShortContent);
                Body = System.Web.HttpUtility.HtmlDecode(Body);

                PermissionTypeCls PermissionTypeCls = Environments.FindPermissionType(
                new GroupNews().PermissionTypes, "GroupNewsItems");
                    NewsCls NewsCls = new NewsBLL().CreateModel(Environments.ActiveLanguage, NewsId);
                GroupNewsItemCls GroupNewsItemCls = new GroupNewsBLL().CreateModelItem(Environments.ActiveLanguage, NewsCls.GroupNewsItemId);
                Environment.Permission.CheckPermission(
                    Environment.Environments.CurrentLoginUser.LoginName,
                    PermissionTypeCls.PermissionTypeCode,   
                             "UpdateRelationNewsItem", GroupNewsItemCls.GroupNewsItemId, GroupNewsItemCls.Owner, true);

                bool CheckOk = Environment.FuncUtilities.checkVnDate(sEntryDate);
                if (CheckOk == false) throw new Exception(ResourceBLL.GetText(WebPartId, "InvalidDate", "Ngày tháng nhập sai!"));
                DateTime EntryDate = Environment.FuncUtilities.VNDateToDate(sEntryDate);

                string ShortContentForSearch=ShortContent;
                string BodyForSearch=Body;
                new NewsBLL().SaveNews(null, ActiveLanguage, GroupNewsItemCls.GroupNewsItemId, NewsId, Subject, ImageUrl, ShortContent, Body, SearchKeyword, Source, EntryDate, AttachedDoc ? 1 : 0, AttachedVideo ? 1 : 0, AttachedImage ? 1 : 0, NewsCls.EmbVideo, NewsCls.EmbAudio);
                return ResourceBLL.GetText(WebPartId,"MessageUpdateRelationNewsOk","Sửa tin tức thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetLoadDataMsg()
        {
            return ResourceBLL.GetText(WebPartId,"LoadingDataText","Đang đọc dữ liệu...");
        }


        [AjaxPro.AjaxMethod]
        public string GetSubject(string ActiveLanguage, string NewsId)
        {
            try
            {
                NewsCls NewsCls = new NewsBLL().CreateModel(ActiveLanguage, NewsId);
                return NewsCls.Subject;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string GetShortContent(string ActiveLanguage, string NewsId)
        {
            try
            {
                NewsCls NewsCls = new NewsBLL().CreateModel(ActiveLanguage, NewsId);
                return NewsCls.ShortContent;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string GetBody(string ActiveLanguage, string NewsId)
        {
            try
            {
                NewsCls NewsCls = new NewsBLL().CreateModel(ActiveLanguage, NewsId);
                return NewsCls.Body;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                string Url = Environment.Environments.GetActiveThemeUrl() + "/Global/Loading.gif";
                return "<img src=\"" + Url + "\"><a class=cssProcessing>" + ResourceBLL.GetText(WebPartId, "ProcessingText", "Đang đọc dữ liệu...") + "</a>";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideAddNewsRelation(string SrcNewsId,string NewsId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new NewsBLL().AddNewsRelation(SrcNewsId, NewsId);
                return GetAlreadyNewsRelation(SrcNewsId);
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideRemoveNewsRelation(string NewsId,string NewsRelationId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new NewsBLL().RemoveNewsRelation(NewsRelationId);
                return GetAlreadyNewsRelation(NewsId);// GetText("RemoveOk", "Loại bỏ tin liên quan thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideSaveNewsRelationIndex(string NewsId, string NewsRelationId,string SortIndex)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new NewsBLL().UpdateNewsRelationSortIndex(NewsRelationId, SortIndex);
                return "";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }
    }
}